package com.enjoy.xbase.dialog;

import android.app.Activity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.enjoy.xbase.R;

public class LoadDialog {
    private Activity activity;
    private View rootView;
    private ImageView ivLoad;
    private TextView tvHint;
    private boolean isShowing;

    public LoadDialog(Activity activity) {
        this.activity = activity;
        isShowing = false;
        rootView = LayoutInflater.from(activity).inflate(R.layout.xbase_dialog_load, null);
        ivLoad = rootView.findViewById(R.id.ic_load);
        tvHint = rootView.findViewById(R.id.tv_hint);
    }

    public void show() {
        show("");
    }

    public void show(String hint) {
        if (activity == null) {
            return;
        }
        if (isShowing) {
            return;
        }
        if (!TextUtils.isEmpty(hint)) {
            tvHint.setText(hint);
        } else {
            tvHint.setText("");
        }
        ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        rootView.setLayoutParams(params);
        decorView.addView(rootView);
        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //dismiss();
            }
        });
        rootView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                return false;
            }
        });
        RotateAnimation rotateAnimation = new RotateAnimation(0, 720f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(1000);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        rotateAnimation.setRepeatMode(Animation.RESTART);
        ivLoad.startAnimation(rotateAnimation);
        isShowing = true;
    }

    public void dismiss() {
        if (!isShowing) {
            return;
        }
        isShowing = false;
        ivLoad.clearAnimation();
        if (rootView.getParent() == null) {
            return;
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        parent.removeView(rootView);
    }

    public boolean isShowing() {
        return isShowing;
    }
}